package com.example.judge.service.impl;

import com.example.common.core.enums.CodeRunStatus;
import com.example.judge.domain.Answer;
import com.example.judge.domain.Question;
import com.example.judge.domain.SandBoxExecuteResult;
import com.example.judge.domain.Task;
import com.example.judge.service.ISandboxPoolService;
import com.github.dockerjava.api.DockerClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SandboxPoolServiceImpl implements ISandboxPoolService {


    @Override
    public SandBoxExecuteResult exeJavaCode(Long userId, String userCode, List<String> inputList) {
        Task task = new Task();
        Question question = new Question();
        question.setCode(userCode);
        List<String> outputList = new ArrayList<>();
        String ExeMessage = "";
        SandBoxExecuteResult sandBoxExecuteResult = new SandBoxExecuteResult();
        for (String input : inputList) {
            Answer answer = task.compileAndRun(question, input);
            if (answer.getError() != 0) {
                SandBoxExecuteResult error = new SandBoxExecuteResult();
                if (answer.getError() == 1) {
                    error.setRunStatus(CodeRunStatus.COMPILE_FAILED);
                } else if (answer.getError() == 2) {
                    error.setRunStatus(CodeRunStatus.FAILED);
                }
                error.setExeMessage(answer.getStderr());
                List<String> errorList = new ArrayList<>();
                errorList.add(answer.getStdout().replace("\r", "").replace("\n", ""));
                error.setOutputList(errorList);
                return error;
            }
            outputList.add(answer.getStdout());
            ExeMessage += answer.getReason();
        }
        sandBoxExecuteResult.setOutputList(outputList);
        sandBoxExecuteResult.setExeMessage(ExeMessage);
        sandBoxExecuteResult.setUseMemory(2L);
        sandBoxExecuteResult.setUseTime(6L);
        sandBoxExecuteResult.setRunStatus(CodeRunStatus.SUCCEED);
        return sandBoxExecuteResult;
    }


}
